/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.mybatis.generator.codegen.mybatis3.xmlmapper.elements;

import com.mouse.fast_sql.constant.Config;
import com.mouse.fast_sql.service.InitService;
import com.mouse.fast_sql.service.InitServiceImpl;
import com.mouse.fast_sql.util.StringUtil;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.GeneratedKey;

import java.util.List;

/**
 * @author Jeff Butler
 */
public class InsertBatchElementGenerator extends
        AbstractXmlElementGenerator {

    public InsertBatchElementGenerator() {
        super();
    }

    @Override
    public void addElements(XmlElement parentElement) {
        //自定义生成类
        InitService initService = new InitServiceImpl();
        initService.init(introspectedTable);


        XmlElement answer = new XmlElement("insert"); //$NON-NLS-1$
        String methodName = introspectedTable.getInsertSelectiveStatementId();
        methodName = "insertBatch";
        answer.addAttribute(new Attribute("id", methodName)); //$NON-NLS-1$

        FullyQualifiedJavaType parameterType = introspectedTable.getRules()
                .calculateAllFieldsClass();
        if (Config.model_flag) {
            parameterType = new FullyQualifiedJavaType(StringUtil.importTran(introspectedTable));
        }
        answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$
                "java.util.List"));

        context.getCommentGenerator().addComment(answer);
        List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
        if (primaryKeyColumns.size() > 0) {
            IntrospectedColumn introspectedColumn = primaryKeyColumns.get(0);
            answer.addAttribute(new Attribute("useGeneratedKeys", "true"));
            answer.addAttribute(new Attribute("keyColumn", introspectedColumn.getActualColumnName()));
            answer.addAttribute(new Attribute("keyProperty", introspectedColumn.getJavaProperty()));
        }
        GeneratedKey gk = introspectedTable.getGeneratedKey();
        if (gk != null) {
            IntrospectedColumn introspectedColumn = introspectedTable
                    .getColumn(gk.getColumn());
            // if the column is null, then it's a configuration error. The
            // warning has already been reported
            if (introspectedColumn != null) {
                if (gk.isJdbcStandard()) {
                    answer.addAttribute(new Attribute("useGeneratedKeys", "true")); //$NON-NLS-1$ //$NON-NLS-2$
                    answer.addAttribute(new Attribute("keyProperty", introspectedColumn.getJavaProperty())); //$NON-NLS-1$
                } else {
                    answer.addElement(getSelectKey(introspectedColumn, gk));
                }
            }
        }

        StringBuilder sb = new StringBuilder();

        sb.append("insert ignore into "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        sb.append("("); //$NON-NLS-1$
        int a = 0;
        StringBuffer sb1 = new StringBuffer();
        for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
            String actualColumnName = introspectedColumn.getActualColumnName();
//            String javaProperty = introspectedColumn.getJavaProperty();
            if (a % 5 == 1) {
                sb1.append("\t\t");
            }
            sb1.append(actualColumnName);
            sb1.append(", ");
            if (a % 5 == 0) {
                sb1.append("\n");
            }
            a++;
        }
        String string = sb1.toString();
        if (string.endsWith("\n")) {
            sb.append(sb1.toString().substring(0, sb1.toString().length() - 3));
        } else if (string.endsWith(", ")) {
            sb.append(sb1.toString().substring(0, sb1.toString().length() - 2));
        }
        sb.append(")");
        sb.append(" values ");
        answer.addElement(new TextElement(sb.toString()));

        XmlElement insertTrimElement = new XmlElement("foreach"); //$NON-NLS-1$
        insertTrimElement.addAttribute(new Attribute("collection", "list")); //$NON-NLS-1$ //$NON-NLS-2$
        insertTrimElement.addAttribute(new Attribute("item", "item")); //$NON-NLS-1$ //$NON-NLS-2$
        insertTrimElement.addAttribute(new Attribute("index", "index")); //$NON-NLS-1$ //$NON-NLS-2$
        insertTrimElement.addAttribute(new Attribute("separator", ",")); //$NON-NLS-1$ //$NON-NLS-2$
        int b = 0;
        StringBuilder sb3 = new StringBuilder();
        sb3.append("( ");
        for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
            String javaProperty = introspectedColumn.getJavaProperty();
            if (b % 5 == 1) {
                sb3.append("\t\t");
            }
            sb3.append("#{item." + javaProperty + "}");
            sb3.append(", ");
            if (b % 5 == 0) {
                sb3.append("\n");
            }
            b++;
        }
        String str = sb3.toString();
        if (str.endsWith("\n")) {
            str = str.substring(0, str.length() - 3);
        } else if (str.endsWith(", ")) {
            str = str.substring(0, str.length() - 2);
        }
        insertTrimElement.addElement(new TextElement(str + ")"));
        answer.addElement(insertTrimElement);

        if (context.getPlugins().sqlMapInsertSelectiveElementGenerated(
                answer, introspectedTable)) {
            parentElement.addElement(answer);
        }
    }
}
